package com.smartfast4j.common.component.fileManager.service.impl;

import com.smartfast4j.common.component.fileManager.bean.UploadResult;
import com.smartfast4j.common.component.fileManager.config.FileUploadType;
import com.smartfast4j.common.component.fileManager.service.FileService;
import com.smartfast4j.common.component.fileManager.util.FileUtil;
import com.smartfast4j.common.util.GUIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 上传文件本地保存
 */
@ConditionalOnProperty(value = "fileManager.type",havingValue = FileUploadType.LOCAL)
@Service
public class LocalFileServiceImpl implements FileService {

    private static Logger logger = LoggerFactory.getLogger(LocalFileServiceImpl.class);

    @Value("${local.fileSavePath}")
    private String fileSavePath; //配置文件的物理保存地址

    @Value("${local.fileUrlPathPattern}")
    private String fileUrlPathPattern; //配置文件的物理保存地址

    @Autowired
    private HttpServletRequest request;//注入request对象

    @Override
    public UploadResult uploadFile(String filePath) {
        return null;
    }

    @Override
    public UploadResult uploadFile(String filePath, String savePath) {
        return null;
    }

    @Override
    public UploadResult uploadFile(InputStream inputStream, String fileName) {
        return null;
    }

    @Override
    public UploadResult uploadFile(MultipartFile multipartFile) {
        UploadResult uploadResult;
        String fileName = multipartFile.getOriginalFilename();// 文件名
        try {
            uploadResult = uploadFile(multipartFile.getBytes(),fileName);
            uploadResult.setFileMd5(FileUtil.getMultipartFileMd5(multipartFile));
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            uploadResult = new UploadResult();
            uploadResult.setOriginalFileName(fileName);
            uploadResult.setIsUploadSuccess(false);
        }
        return uploadResult;
    }

    @Override
    public List<UploadResult> uploadFile(List<MultipartFile> multipartFiles) {
        List<UploadResult> uploadResultList = new ArrayList<>();
        multipartFiles.forEach(item->{
            UploadResult uploadResult = uploadFile(item);
            uploadResultList.add(uploadResult);
        });
        return uploadResultList;
    }

    @Override
    public List<UploadResult> uploadFile(Map<String, InputStream> inputStreamMap) {
        return null;
    }

    @Override
    public UploadResult uploadFile(InputStream inputStream, String fileName, String savePath) {
        return null;
    }

    @Override
    public List<UploadResult> uploadFile(Map<String, InputStream> inputStreamMap, String savePath) {
        return null;
    }

    @Override
    public UploadResult uploadFile(File file, String savePath) {
        return null;
    }

    @Override
    public UploadResult uploadFile(byte[] fileByte, String fileName) {
       return uploadFile(fileByte, fileName,null);
    }

    @Override
    public UploadResult uploadFile(byte[] fileByte, String fileName, String savePath) {
        UploadResult uploadResult = new UploadResult();
        try {
            if(StringUtils.isNotEmpty(savePath)){
                if(savePath.startsWith("/")){
                    fileSavePath = fileSavePath + savePath;
                }else {
                    fileSavePath = fileSavePath  + "/" + savePath;
                }
            }
            File file = new File(fileSavePath);
            if(!file.exists()){
                file.mkdirs();//创建目录
            }
            String fileSuffix = fileName.substring(fileName.indexOf("."));
            String newFileName = GUIDUtil.genRandomGUID()+fileSuffix;
            String filePath = fileSavePath + "/" + newFileName;
            FileUtil.saveFile(filePath,fileByte);
            uploadResult.setFileSuffix(fileSuffix);//后缀
            String fileUrl = getFileUrl(newFileName);//访问URL
            uploadResult.setFileUrl(fileUrl);
            uploadResult.setNewFileName(newFileName);
            uploadResult.setIsUploadSuccess(true);
            uploadResult.setOriginalFileName(fileName);
            uploadResult.setSavePath(filePath);
            uploadResult.setStorageType("local");
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        }
        return uploadResult;
    }

    @Override
    public UploadResult uploadNetworkFile(String fileUrl) throws MalformedURLException {
        return uploadNetworkFile(fileUrl,"");
    }

    @Override
    public UploadResult uploadNetworkFile(String fileUrl, String fileExt) throws MalformedURLException {
        byte[] content = FileUtil.downloadNetworkFile(fileUrl);
        String ext;
        if (StringUtils.isNotEmpty(fileExt)) {
            ext = fileExt;
        } else {
            ext = fileUrl.substring(fileUrl.lastIndexOf(".") + 1).toLowerCase();
        }
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1).toLowerCase() + "." + ext;
        return this.uploadFile(content, fileName);
    }

    @Override
    public int deleteFile(String directory, String fileName) {
        return 0;
    }

    @Override
    public Map<String, Integer> batchDeleteFile(String directory, List<String> lstFileName) {
        return null;
    }

    @Override
    public byte[] downloadFile(String fileUrl) {
        return new byte[0];
    }

    @Override
    public byte[] downloadFile(String directory, String fileName) {
        return new byte[0];
    }

    @Override
    public void downloadFile(String directory, String fileName, String savePath) {

    }

    @Override
    public void downFile(HttpServletResponse response, String fileUrl, String fileName) {

    }

    /**
     * 获取本地上传文件访问URL
     * @param newFileName
     * @return
     * @throws UnknownHostException
     */
    private String getFileUrl(String newFileName) throws UnknownHostException {
        String domain = request.getServerName();//获取服务器域名
        int port = request.getServerPort();//获取服务器端口
        InetAddress address= InetAddress.getByName(request.getServerName());
        String ip = address.getHostAddress();//获取服务器IP地址
        String fileUrl = String.format("http://%s:%s%s%s",ip,port,fileUrlPathPattern.replaceAll("\\*",""),newFileName);//访问URL
        return fileUrl;
    }
}
